﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RentHouse.Common;
using RentHouse.Service;
using RentHouse.DTO;
using RentHouse.IService;
using RentHouse.Service.Entities;
namespace RentHouse.Service
{
    public class RolesService : IRolesService
    {


     public List<RolesAddDTO> GetList(int length, int start,string name,ref int rowCount)
        {
            using (var model = new RentHouseContext())
            {
                var db = new BaseService<T_Roles>(model);
                var query = PredicateExtensions.True<T_Roles>();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    query = query.And(e => e.Name.Contains(name));
                }
                var list = db.GetPagedList(start,length,ref rowCount, query, e=>e.Id,false).Select(e => new RolesAddDTO
                {
                    Id= e.Id,
                    Name= e.Name,
                }).ToList();
                return list;
            
            }
        }


        public List<PermissionDTO> GetAdd()
        {
            using (var model = new RentHouseContext())
            {
                var db = new BaseService<T_Permissions>(model);
                var list =  db.GetList(e=>true).Select(e => new PermissionDTO
                {
                    Id = e.Id,
                    Name = e.Name,
                    Description=e.Description
                }).ToList();
                return  list;

            }
        }

        public async Task<List<PermissionDTO>> GetAddAsync()
        {
            return await Task.Run(() => GetAdd());
         
        }

        public AjaxResult AddRole(RolesAddDTO dTO)
        {
            using (var db = new RentHouseContext())
            {
                var roles = new BaseService<T_Roles>(db);
                var permissions= new BaseService<T_Permissions>(db);
                T_Roles t_Roles = new T_Roles
                {
                    CreateDateTime = DateTime.Now,
                     IsDeleted=false,
                     Name=dTO.Name,
                };
                foreach (var item in dTO.PermissionIds)
                {
                    T_Permissions t_Permissions = permissions.Get(e => e.Id == item);
                    t_Roles.T_Permissions.Add(t_Permissions);
                }
                if (roles.Add(t_Roles) >0)
                {
                    return new AjaxResult(ResultState.Success, "添加成功");
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "添加失败");

                }
            }
        }

        public async Task<AjaxResult> AddRoleAsync(RolesAddDTO dTO)
        {
            return await Task.Run(() => AddRole(dTO));

        }

        public RoleEditDTO GetEditRole(long id)
        {
            using (var db = new RentHouseContext())
            {
                var bs = new BaseService<T_Roles>(db);
                var permissions = new BaseService<T_Permissions>(db);
                var role = bs.Get(e => e.Id == id);
                if (role != null)
                {
                    RoleEditDTO dto = new RoleEditDTO
                    {
                        Id = role.Id,
                        Name = role.Name
                    };
                    //需要获取当前用户的权限，并且做上标记
                    //1.先获取所有权限列表
                    var permissionsList = permissions.GetList(e => true);
                    //获取该角色的权限列表
                    var rolePermission = role.T_Permissions;
                    //实例化角色所拥有权限的泛型集合
                    dto.PermissionsList = new List<RolePermissionEdit>();
              
                    foreach (var item in permissionsList)
                    {
                        RolePermissionEdit permissionEdit = new RolePermissionEdit
                        {
                            Description = item.Description,
                            Id = item.Id,
                            Name = item.Name,
                            //需要在这里增加一个标识，来表示当前是个权限是该角色所拥有的
                            IsUsed = rolePermission.Any(e => e.Id == item.Id)
                        };
                        dto.PermissionsList.Add(permissionEdit);
                    }
                    return dto;

                }
                return null;
            }
        
        }

        public AjaxResult Edit(RolesAddDTO dTO)
        {
            using (var db = new RentHouseContext())
            {
                var roles = new BaseService<T_Roles>(db);
                var permissions = new BaseService<T_Permissions>(db);
                //查询当前角色信息
                T_Roles t_Roles = roles.Get(e=>e.Id==dTO.Id);
                //修改当前角色信息，并且将该角色权限清空
                t_Roles.Name = dTO.Name;
                t_Roles.T_Permissions.Clear();
                //循环选择的权限，为该角色重新添加权限
                foreach (var item in dTO.PermissionIds)
                { 
                    T_Permissions t_Permissions = permissions.Get(e => e.Id == item);
                    t_Roles.T_Permissions.Add(t_Permissions);
                }
                if (db.SaveChanges() > 0)
                {
                    return new AjaxResult(ResultState.Success, "修改成功");
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "修改失败");

                }
            }
        }

        public AjaxResult Delete(long id)
        {
            using (var db = new RentHouseContext())
            {
                BaseService<T_Roles> service = new BaseService<T_Roles>(db);
                var result = service.Get(e => e.Id == id);
                result.T_Permissions.Clear();
               ;
                if (service.Delete(result))
                    return new AjaxResult(ResultState.Success, "删除成功");
                else
                   return new AjaxResult(ResultState.Success, "删除失败");

            }
        }

        public AjaxResult Deletes(long [] id)
        {
            try
            {
                foreach (var item in id)
                {
                    Delete(item);
                }
                return new AjaxResult(ResultState.Success, "删除成功");

            }
            catch (Exception)
            {
                return new AjaxResult(ResultState.Success, "删除失败");

            }

        }

        public List<RolesDTO> GetList()
        {
            using (var model = new RentHouseContext())
            {
                var db = new BaseService<T_Roles>(model);
                var list = db.GetList(e => true).Select(e => new RolesDTO
                {
                    Id = e.Id,
                    Name = e.Name
                }).ToList();
                return list;

            }
        }
    }
}
